<template>
	<view class="pages">
		<u-navbar title="下销售清单" placeholder bgColor="#fff" @leftClick="leftClick"></u-navbar>
		<view class="top-search">
			<view class="search-type" @click="pickerType = 'type'">{{ form.typeName }}
			  <u-icon name="arrow-down" size="24rpx"></u-icon>
			</view>
			<view class="top-input">
				<u--input
					placeholder="名称|条码|规格"
					border="surround"
					shape="circle"
					v-model="searchVal"
					@blur="blur"
				></u--input>
				<!-- <view class="btn" @click="pdaScanCode">
					PDA扫码
				</view> -->
				<image src="../../static/search.png" mode="widthFix"></image>
			</view>
			<view class="" @click="pdaScanCode">
				<u-icon name="scan" size="30"></u-icon>
			</view>
		</view>
		<view class="form-data">
			<u--form
				labelPosition="left"
				:model="orderData"
			>
				<u-form-item
					label="客户"
					borderBottom
					required
					@click="jumpTo('/other/salesOrder/salesOrder', {type: '1'})"
				>
					<u--input
						v-model="orderData.userInfo.name"
						disabled
						disabledColor="#ffffff"
						placeholder="请选择客户"
						border="none"
					></u--input>
					<u-icon
						slot="right"
						name="arrow-right"
					></u-icon>
				</u-form-item>
				<u-form-item
					label="客户电话"
					borderBottom
				>
					<u--input
						v-model="orderData.userInfo.phone"
						disabled
						disabledColor="#ffffff"
						placeholder="请填写客户电话"
						border="none"
					></u--input>
				</u-form-item>
				
				<view class="" v-show="dataListShow">
					<!-- <u-form-item
						label="仓库"
						borderBottom
						required
						@click="jumpTo('/pages/depot/depotPage')"
					>
						<u--input
							v-model="orderData.userInfo.warehouse"
							disabled
							disabledColor="#ffffff"
							placeholder="请选择仓库"
							border="none"
						></u--input>
						<u-icon
							slot="right"
							name="arrow-right"
						></u-icon>
					</u-form-item> -->
					<u-form-item
						label="单据日期"
						borderBottom
						required
						@click="showDateTime = true"
					>
						<u--input
							v-model="orderData.userInfo.invoicesDate"
							disabled
							disabledColor="#ffffff"
							placeholder="请选择单据日期"
							border="none"
						></u--input>
						<u-icon
							slot="right"
							name="arrow-right"
						></u-icon>
					</u-form-item>
					<u-form-item
						label="业务员"
						borderBottom
						required
						@click="jumpTo('/pages/depot/depotPage')"
					>
						<u--input
							v-model="orderData.userInfo.salesman"
							disabled
							disabledColor="#ffffff"
							placeholder="请选择业务员"
							border="none"
						></u--input>
						<u-icon
							slot="right"
							name="arrow-right"
						></u-icon>
					</u-form-item>
					<u-form-item
						label="部门"
						borderBottom
						required
					>
						<u--input
							v-model="orderData.userInfo.department"
							disabled
							disabledColor="#ffffff"
							placeholder="请选择部门"
							border="none"
						></u--input>
						<!-- <u-icon
							slot="right"
							name="arrow-right"
						></u-icon> -->
					</u-form-item>
					<!-- <u-form-item
						label="排尺员"
						borderBottom
					>
						<u--input
							v-model="orderData.userInfo.paichiyuan"
							placeholder="请填写排尺员"
							border="none"
						></u--input>
					</u-form-item> -->
					<u-form-item
						label="单据类型"
						borderBottom
						required
						@click="this.copyDataId?'':showOrderType = true"
					>
						<u--input
							v-model="orderData.userInfo.orderType.name"
							disabled
							disabledColor="#ffffff"
							placeholder="请选择单据类型"
							border="none"
						></u--input>
						<u-icon
							slot="right"
							name="arrow-right"
						></u-icon>
					</u-form-item>
					<u-form-item
						label="是否开发票"
						borderBottom
						@click="showInvoiceClick"
					>
						<u--input
							v-model="orderData.userInfo.invoice"
							disabled
							disabledColor="#ffffff"
							placeholder="请选择是否开票"
							border="none"
						></u--input>
						<u-icon
							slot="right"
							name="arrow-right"
						></u-icon>
					</u-form-item>
					<u-form-item
						label="备注"
						borderBottom
					>
						<u--input
							v-model="orderData.userInfo.remark"
							disabledColor="#ffffff"
							placeholder="请填写备注"
							border="none"
						></u--input>
					</u-form-item>
				</view>
				<view class="foldBtn" v-if="dataListShow" @click="dataListShow = !dataListShow">
					<view class="" style="margin-right: 12rpx;">收起</view>
					<u-icon name="arrow-up"></u-icon>
				</view>
				<view class="foldBtn" v-else @click="dataListShow = !dataListShow">
					<view class="" style="margin-right: 12rpx;">完整信息</view>
					<u-icon name="arrow-down"></u-icon>
				</view>
			</u--form>
		</view>
		<view class="goods-box">
			<view class="title">商品列表</view>
			<view class="goods-data" v-if="orderData.goodsList.length != 0">
				<view class="goods-list" v-for="(item, index) in orderData.goodsList" :key="index" :id="'item-' + index">
					<view class="list-name">
						<view class="name u-line-2" @click="toPage(item)">{{index+1}} . {{item.FmaterialName}} ({{item.FmaterialNumber}})</view>
						<u-icon name="photo" size="24" @click="imageBig(item.FmaterialNumber)"></u-icon>
						<view class="" @click="toForm(item)"><u-icon name="file-text" size="24"></u-icon></view>
						<view class="" @click="toDelete(item, index)"><u-icon name="trash" size="24"></u-icon></view>
						<u-icon name="arrow-right" size="24" @click="toPage(item)"></u-icon>
					</view>
					<view class="list-price">
						<view class="number">
							<view class="">单价：</view>
							<u--input
								placeholder="请输入单价"
								v-model="item.RetailPrice"
								border="bottom"
								@blur="priceBlur($event, index, item)"
								@focus="priceFocus"
							></u--input>
							<view class="">元</view>
						</view>
						<view class="number">
							<view class="">数量：</view>
							<u--input
								placeholder="请输入数量"
								v-model="item.shopCarNum"
								@blur="numBlur($event, index, item)"
								border="bottom"
							></u--input>
						</view>
					</view>
					<view class="list-price">
						<view class="number">
							<view class="">库存单位：</view>
							<view class="">{{item.UnitName}}</view>
						</view>
						<view class="number" @click="unitClick(item, index)">
							<view class="">计价单位：</view>
							<view class="">{{item.priceUnit}}</view>
						</view>
					</view>
					<view class="list-price">
						<!-- <view class="price">
							<view class="" style="margin-right: 20rpx;">赠品</view>
							<u-switch :value="item.goodsGifts" @change="giftsClick(index, item)" ></u-switch>
						</view> -->
						<view class="number">
							<view class="u-line-1">商品属性：{{item.Attributes}}</view>
						</view>
						<view class="number">
							<!-- <view class="">金额：{{ item.goodsGifts ? 0 : (Number(item.RetailPrice) * Number(item.shopCarNum)).toFixed(2) }}</view> -->
							<view class="">金额：{{ (Number(item.RetailPrice) * Number(item.shopCarNum)).toFixed(2) }}</view>
						</view>
					</view>
					<view class="list-price">
						<view class="textarea">
							<view class="">备注：</view>
							<u--textarea v-model="item.remark" placeholder="请填写备注" autoHeight @blur="remarkBlur($event, index, item)"></u--textarea>
						</view>
					</view>
				</view>
			</view>
			<view class="goods-null" v-else>
				您还没有选存货~
			</view>
		</view>
		<view class="bottom-box">
			<view class="top-list">
				<view class="">
					合计：<text style="color: red;">￥{{totalPrice}}</text>
				</view>
				<view class="">
					共{{productTypesCount}}种，数量合计：{{total}}
				</view>
			</view>
			<view class="list">
				<view class="one" @click="jumpTo('/other/salesOrder/stocksPage')">选存货</view>
				<view class="two" @click="getPrice">取价</view>
				<view class="three" @click="toPay" v-if="orderData.goodsList.length != 0">结算</view>
			</view>
		</view>
		<u-modal
			:show="showNum"
			title="请填写商品数量"
			showCancelButton
			@confirm="numConfirm(goodsInfo.FmaterialNumber)"
			@cancel="showNum = false"
		>
			<view class="goodsNum-modal">
				<view class="">{{goodsInfo.FmaterialName}}（{{goodsInfo.FmaterialNumber || ''}}）</view>
				<view class="" style="display: flex; margin-bottom: 10rpx;">
					<view class="">零售价：{{goodsInfo.RetailPrice || ''}}</view>
				</view>
				<view class="" style="display: flex; margin-bottom: 10rpx;">
					<view class="" style="margin-right: 8rpx;">可用量：{{goodsInfo.UseQty || 0}}{{goodsInfo.UnitName}}</view>
					<view class="">现存量：{{goodsInfo.ExistQty || 0}}{{goodsInfo.UnitName}}</view>
				</view>
				<u--input
					placeholder="请输入数量"
					border="surround"
					type="number"
					v-model="goodsNumber"
				></u--input>
			</view>
		</u-modal>

		<u-picker
			:show="showInvoice"
			:columns="invoiceActions"
			@cancel="showInvoice = false"
			@confirm="invoiceSelect"
			keyName="AssistantName"
		></u-picker>
		
		<u-picker
			:show="showOrderType"
			:columns="orderActions"
			@cancel="showOrderType = false"
			@confirm="orderConfirm"
			keyName="name"
		></u-picker>
		<u-overlay :show="overlayShow" @click="overlayShow = false">
			<image class="overlayImage" :src="overlayImg" mode="widthFix"></image>
			<view class="saveBase" @click="saveBase">保存图片</view>
		</u-overlay>
		<u-datetime-picker
			:show="showDateTime"
			@cancel="showDateTime = false"
			@confirm="confirmDate"
			v-model="datetimeValue"
			mode="date"
		></u-datetime-picker>
		<u-modal
			:show="unloadShow"
			title="提示"
			content='是否将数据存入草稿'
			showCancelButton
			@confirm="unloadConfirm"
			@cancel="unloadCancel"
		></u-modal>
		<u-modal
			:show="againShow"
			title="提示"
			content='当前列表中已存在该商品,是否再次添加？'
			showCancelButton
			@confirm="againConfirm"
			@cancel="againCancel"
		></u-modal>
		<u-modal
			:show="goodsDeleteShow"
			title="提示"
			:content="delGoodsContent"
			showCancelButton
			@confirm="deleteConfirm"
			@cancel="goodsDeleteShow = false"
		></u-modal>
		<u-modal
			:show="cacheShow"
			title="提示"
			content='由于意外退出,您有一封尚未提交的单据,是否恢复？'
			showCancelButton
			@confirm="cacheConfirm"
			@cancel="cacheCancel"
		></u-modal>
		<u-modal :show="goodsInfoShow" title="物料详情" @confirm="goodsInfoShow = false">
			<view class="goodsView">
				<view class="goods-info">
					<view class="u-line-1" style="width: 50%;"><text style="color: #b2b2b2;">现存量：</text>{{goodsForm.ExistQty}}</view>
					<view class="u-line-1" style="width: 50%;"><text style="color: #b2b2b2;">可用量：</text>{{goodsForm.UseQty}}</view>
				</view>
				<view class="goods-info">
					<view class="u-line-1" style="width: 50%;"><text style="color: #b2b2b2;">商品重量：</text>{{ goodsForm.FmaterialWeight }}</view>
					<view class="u-line-1" style="width: 50%;"><text style="color: #b2b2b2;">采购员：</text>{{ goodsForm.PurChaser }}</view>
				</view>
				
				<view class="goods-info">
					<view class="u-line-1" style="width: 50%;"><text style="color: #b2b2b2;">零售价：</text>{{ goodsForm.RetailPrice }}</view>
					<view class="u-line-1" style="width: 50%;"><text style="color: #b2b2b2;">单价：</text>{{ goodsForm.RetailPrice }}</view>
				</view>
				<view class="goods-info">
					<view class="u-line-1" style="width: 50%;"><text style="color: #b2b2b2;">库存单位：</text>{{goodsForm.UnitName}}</view>
					<view class="u-line-1" style="width: 50%;"><text style="color: #b2b2b2;">计价单位：</text>{{goodsForm.priceUnit}}</view>
				</view>
				<view class="goods-info">
					<view class="u-line-1"><text style="color: #b2b2b2;">物料分组：</text>{{ goodsForm.FmaterialGroup }}</view>
				</view>
				<view class="goods-info">
					<view class="u-line-1"><text style="color: #b2b2b2;">商品属性：</text>{{ goodsForm.Attributes }}</view>
				</view>
				<view class="goods-info">
					<view class="u-line-1"><text style="color: #b2b2b2;">包装量：</text>{{ goodsForm.FmaterialQty }}</view>
				</view>
				<view class="goods-info">
					<view class="u-line-3"><text style="color: #b2b2b2;">商品描述：</text>{{ goodsForm.FmaterialDes }}</view>
				</view>
			</view>
		</u-modal>
		<u-picker :show="unitShow" :columns="columns" keyName="name" @cancel="unitShow = false" @confirm="confirmUnit"></u-picker>
		<u-picker ref="uPicker" :show="pickerType!=''" :columns="[pickerInfo[pickerType]]" keyName="name" @confirm="pickerConfirm" @cancel="pickerType = ''"></u-picker>
	</view>
</template>

<script>
	import { getExecuteServiceAll, dynamicFormServiceSave, getOrderInvoice, getOrderSalesman, getExecuteServiceImg, getBaseImg, getMaterialInformation } from '@/api/index'
	import { formatTime, formatTimeTwo } from '../../common/util.js'

	export default {
	  data() {
	    return {
				id: '',
				orgInfo: {},
				userInfo: {},
				searchVal: '',
				showDateTime: false,
				dataListShow: false,
				unloadShow: false,
				againShow: false,
				goodsDeleteShow: false,
				giftsShow: true,
				showNum: false,
				overlayShow: false,
				showInvoice: false,
				cacheShow: false,
				showOrderType: false,
				goodsInfoShow: false,
				goodsForm: {},
				orderIndex: 0,
				orderData: {
					userInfo: {
						name: '',
						remark: '',
						invoicesDate: '',
						phone: '',
						department: '',
						departmentNum: '',
						salesman: '',
						salesmanNum: '',
						orderType: { name: '下单', id: 'XSDD01_SYS' },
						invoice: '',
						invoiceNum: '',
					},
					goodsList: [],
				},
				invoiceActions: [],
				orderActions: [[ { name: '下单', id: 'XSDD01_SYS' }, { name: '退货', id: 'XSDD05_SYS' } ]],
				// 物料编码：Materidal。规格型号：ModelName。物料名称：MaterialName
				pickerType: '',
				pickerInfo: {
				  type: [
						{
						  id: 'Materidal',
						  name: '物料编码'
						},
				    {
				      id: 'MaterialName',
				      name: '物料名称',
				    },
				    {
				      id: 'ModelName',
				      name: '规格型号'
				    },
				  ],
				},
				form: {
				  typeName: '物料编码',
				  type: 'Materidal',
				},
				radio: '',
				switchVal: false,
				goodsNumber: '',
				overlayImg: '',
				goodsInfo: {},
				datetimeValue: '',
				option: {},
				oldPriceValue: '',
				// 判断是否是复制的数据
				copyText: '',
				// 删除商品索引
				delGoodsIndex: '',
				// 删除商品提示内容
				delGoodsContent: '',
				// 计价单位相关
				columns: [],
				unitIndex: 0,
				unitShow: false,
				copyDataId: '',
	    }
	  },
	  onLoad(option) {
			this.option = option
			this.orgInfo = uni.getStorageSync('orgInfo')
			this.userInfo = uni.getStorageSync('userInfo')
			this.datetimeValue = formatTimeTwo(new Date(), 'Y-M-D')
			// 草稿页进入，销售订单不自动恢复
			if(this.option.dateIndex && this.option.dateIndex < uni.getStorageSync('draftList').length) {
				// 获取草稿列表
				let draft = uni.getStorageSync('draftList') || []
				// 页面回显
				let dateForm = draft[this.option.dateIndex]
				// 删除当前草稿
				draft.splice(this.option.dateIndex, 1)
				// 重新存入
				uni.setStorageSync('draftList', draft)
				// 页面赋值
				this.orderData = dateForm
			} else if(option.copyText) {
				this.copyText = option.copyText
				// 复制页进入
				let copy = uni.getStorageSync('copyDataList')
				this.copyDataId = uni.getStorageSync('copyDataId')
				console.log(copy)
				// 下单信息
				this.orderData.userInfo.name = copy[0]['FCustId.FName']
				// this.orderData.userInfo.invoicesDate = copy[0].FDate.substring(0, 10)
				// 当前日期
				this.orderData.userInfo.invoicesDate = formatTimeTwo(new Date(), 'Y-M-D')
				this.orderData.userInfo.phone = copy[0]['FCustId.FNumber']
				this.orderData.userInfo.department = copy[0]['FSaleDeptId.FName']
				this.orderData.userInfo.departmentNum = copy[0]['FSaleDeptId.FNumber']
				this.orderData.userInfo.salesman = copy[0]['FSalerId.FName']
				this.orderData.userInfo.salesmanNum = copy[0]['FSalerId.FNumber']
				this.orderData.userInfo.invoice = copy[0]['F_PCYE_Assistant_SFKFP.FDATAVALUE']
				this.orderData.userInfo.invoiceNum = copy[0]['F_PCYE_Assistant_SFKFP.FNumber']
				this.orderData.userInfo.orderType.name = copy[0]['FBillTypeID.FName']
				this.orderData.userInfo.orderType.id = copy[0]['FBillTypeID.FNumber']
				this.orderData.userInfo.remark = copy[0].FNote
				this.orderData.goodsList = copy
				// 商品信息
				copy.forEach(item => {
					item.FmaterialName = item.fmaterialname
					item.FmaterialNumber = item['FMaterialId.FNumber']
					item.RetailPrice = item.ftaxprice 
					item.shopCarNum = item.fpriceunitqty
					item.UnitName = item['funitid.fname']
					item.priceUnit = item['funitid.fname']
					item.UnitNameNum = item['funitid.fnumber']
					item.priceUnitNum = item['funitid.fnumber']
					item.FmaterialWeight = item['FMaterialId.FNETWEIGHT']
					item.Attributes = item['FMaterialId.F_PCYE_Assistant_apv']
					item.FmaterialQty = item['FMaterialId.F_PCYE_Text_83g1']
					item.FmaterialDes = item['FMaterialId.FDescription']
					item.PurChaser = item['FMaterialId.FPurchaserId']
					item.FmaterialGroup = item['FMaterialId.FPurchaserId']
					item.ExistQty = item['FMaterialId.FPurchaserId']
					item.UseQty = item['FMaterialId.FPurchaserId']
					item.remark = item.FEntryNote
				})
				uni.removeStorageSync('copyDataList')
				uni.removeStorageSync('copyDataId')
			} else {
				// 如果有缓存数据，打开是否恢复弹窗
				if(uni.getStorageSync('orderDataCache')) {
					this.cacheShow = true
					return
				}
				this.cacheCancel()
			}
	  },
		onShow() {
			if( uni.getStorageSync('gwc_key').length != 0 ) {
				this.orderData.goodsList = [ ...this.orderData.goodsList, ...uni.getStorageSync('gwc_key') ]
				uni.removeStorageSync('gwc_key')
			}
		},
		watch: {
			// 销售订单自动恢复
			orderData: {
				handler(newValue) {
					// 只有当页面加载完成且 orderData 发生变化时，才将其存入缓存
					if(!this.copyDataId) {
						uni.setStorageSync('orderDataCache', newValue)
					}
				},
				deep: true // 深度监听，确保能监听到对象内部属性的变化
			}
		},
		computed: {
			totalPrice: function () {
				let sum = 0;
				for (let i = 0; i < this.orderData.goodsList.length; i++) {
					let aa = Number(this.orderData.goodsList[i].RetailPrice)
					let bb = Number(this.orderData.goodsList[i].shopCarNum)
					sum = sum + aa*bb
				}
				return sum.toFixed(2)
			},
			total: function () {
				let sum = 0;
				for (let i = 0; i < this.orderData.goodsList.length; i++) {
					sum = sum + Number(this.orderData.goodsList[i].shopCarNum)
				}
				return sum
			},
			productTypesCount() {
				const uniqueIds = new Set();
				for (let i = 0; i < this.orderData.goodsList.length; i++) {
					uniqueIds.add(this.orderData.goodsList[i].FmaterialNumber);
				}
				return uniqueIds.size;
			}
		},
	  methods: {
			// 取价
			getPrice() {
				uni.showLoading({ mask: true });
				this.orderData.goodsList.forEach((item, index) => {
					const parameters = {
					  Materidal: item.FmaterialNumber,
					  ModelName: '',
					  MaterialName: '',
						orgNumber: this.orgInfo.orgId
					}
					getExecuteServiceAll({json: JSON.stringify(parameters)}).then(res => {
						if(res.Material[0].FmaterialName) {
							item.RetailPrice = res.Material[0].RetailPrice
							this.$set(this.orderData.goodsList, index, item)
						} else {
							uni.showToast({
								title: res.Material[0].msg,
								icon: 'none'
							});
						}
					})
				})
				uni.hideLoading();
			},
			// 查询项
			pickerConfirm(e) {
			  if(e.value[0].id) {
			    this.form[this.pickerType] = e.value[0].id
			    this.form[this.pickerType+'Name'] = e.value[0].name
			  } else {
			    this.form[this.pickerType] = ''
			    this.form[this.pickerType+'Name'] = ''
			  }
			  this.pickerType = ''
			  this.searchValue = ''
			},
			// 获取焦点触发
			priceFocus(e) {
				this.oldPriceValue = e.target.value
			},
			// 修改金额触发
			priceBlur(e, index, item) {
				if(Number(e) < Number(this.oldPriceValue)) {
					uni.showToast({
						title: '单价不能小于原单价',
						icon: 'none'
					});
					item.RetailPrice = Number(this.oldPriceValue).toFixed(2)
					this.$set(this.orderData.goodsList, index, item)
					// this.orderData.goodsList[index].RetailPrice = Number(this.oldPriceValue).toFixed(2)
				} else {
					item.RetailPrice = Number(e).toFixed(2)
					this.$set(this.orderData.goodsList, index, item)
					// this.orderData.goodsList[index].RetailPrice = Number(e).toFixed(2)
				}
			},
			numBlur(e, index, item) {
				item.shopCarNum = e
				this.$set(this.orderData.goodsList, index, item)
			},
			remarkBlur(e, index, item) {
				item.remark = e.target.value
				this.$set(this.orderData.goodsList, index, item)
			},
			showInvoiceClick() {
				this.showInvoice = true
				this.invoiceActions = []
				this.getInvoicePage()
			},
			// 是否开发票
			getInvoicePage() {
				uni.showLoading({ mask: true });
				getOrderInvoice({}).then(res => {
					if(res.AssistantList.length != 0) {
						uni.hideLoading();
						this.invoiceActions.push(res.AssistantList)
					} else {
						uni.showToast({
							title: '暂无数据',
							icon: 'none'
						});
					}
				})
			},
			// 业务员
			getSalesmanPage() {
        getOrderSalesman({ "parameters": [ {"FuserAccount": this.userInfo.UserName, "orgNumber":this.orgInfo.orgId, "FOperatorType":"XSY"} ]}).then(res => {
					if(res.IsSuccess) {
						this.orderData.userInfo.salesman = res.OperName
						this.orderData.userInfo.salesmanNum = res.OperNumber
						this.orderData.userInfo.department = res.PartName
						this.orderData.userInfo.departmentNum = res.PartNumber
					}
				})
			},
			cacheCancel() {
				// 业务员
				this.getSalesmanPage()
				this.cacheShow = false
				if(this.option.name || this.option.phone) {
					// 如果这里添加字段 /other/salesOrder/salesOrder 也需要添加
					this.orderData.userInfo.name = this.option.name
					this.orderData.userInfo.phone = this.option.phone
					this.orderData.userInfo.invoicesDate = formatTimeTwo(new Date(), 'Y-M-D')
				} else {
					this.reLaunch('/pages/index/index')
				}
			},
			// 意外退出恢复之前的数据
			cacheConfirm() {
				this.orderData = uni.getStorageSync('orderDataCache')
				this.cacheShow = false
			},
			// 供业务员页面调用的方法
			onPageBReturn(data) {
				this.orderData.userInfo.salesman = data.data.OperName
				this.orderData.userInfo.salesmanNum =  data.data.OperNumber
				this.orderData.userInfo.department =  data.data.PartName
				this.orderData.userInfo.departmentNum =  data.data.PartNumber
			},
			// 选择日期
			confirmDate(e) {
				this.orderData.userInfo.invoicesDate = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
				this.showDateTime = false
			},
			// 点击开关赠品
			giftsClick(index, item) {
				item.goodsGifts = !item.goodsGifts
				this.$set(this.orderData.goodsList, index, item)
			},
			// 点击删除某条商品
			toDelete(item, index) {
				this.delGoodsIndex = index
				this.delGoodsContent = '是否删除：'+ item.FmaterialName + '(' + item.FmaterialNumber + ') 商品'
				this.goodsDeleteShow = true
			},
			deleteConfirm() {
				this.orderData.goodsList.splice(this.delGoodsIndex, 1)
				this.goodsDeleteShow = false
			},
			blur() {
				if(this.searchVal.trim()!== '') {
					uni.showLoading({ mask: true });
          // 物料编码：Materidal。规格型号：ModelName。物料名称：MaterialName
          const parameters = {
            Materidal: '',
            ModelName: '',
            MaterialName: '',
						orgNumber: this.orgInfo.orgId
          }
					if(this.form.type == 'Materidal') {
						parameters.Materidal = this.searchVal
					} else if(this.form.type == 'MaterialName') {
						parameters.MaterialName = this.searchVal
					} else {
						parameters.ModelName = this.searchVal
					}
					getExecuteServiceAll({json: JSON.stringify(parameters)}).then(res => {
						uni.hideLoading();
						if(res.Material[0].FmaterialName) {
							// 数量为一条，直接本页添加，为多条跳转选存货
							if(res.Material.length == 1) {
								this.showNum = true
								// 输入框清零
								this.goodsNumber = ''
								// 存入赠品字段
								res.Material.forEach(item => {
									// item.goodsGifts = false
									item.remark = ''
									item.shopCarNum = 0
									item.priceUnit = item.UnitName
									item.priceUnitId = item.UnitFnumber
								})
								this.goodsInfo = res.Material[0]
							} else {
								this.jumpTo('/other/salesOrder/stocksPage', {search: this.searchVal, typeName: this.form.typeName, type: this.form.type})
							}
						} else {
							uni.showToast({
								title: res.Material[0].msg,
								icon: 'none'
							});
						}
					})
				} else {
					uni.showToast({
						title: '请输入内容',
						icon: 'none'
					});
				}
			},
			leftClick() {
				if(!this.copyDataId) {
					this.unloadShow = true
					// 点击返回 清除销售订单自动恢复的缓存
					uni.removeStorageSync('orderDataCache')
				} else {
					uni.navigateBack({
						delta: 1,
					})
				}
			},
			// 点击返回确定触发
			unloadConfirm() {
				this.unloadShow = false
				// 创建时间
				this.orderData.creatDate = formatTime(new Date())
				// 总金额
				this.orderData.totalPrice = this.totalPrice
				// 组织id
				this.orderData.orgId = this.orgInfo.orgId
				let draft = []
				draft = uni.getStorageSync('draftList') || []
				draft.unshift(this.orderData)
				// 存入草稿
				uni.setStorageSync('draftList', draft)
				uni.navigateBack({
					delta: 1,
				})
			},
			unloadCancel() {
				this.unloadShow = false
				uni.navigateBack({
					delta: 1,
				})
			},
			// 扫描触发
			pdaScanCode() {
				let that = this
				// 调起条码扫描
				uni.scanCode({
					scanType: ['barCode'],
					success: function (res) {
						uni.showLoading({ mask: true });
						// const parameters = [res.result]
						const parameters = {
						  Materidal: res.result,
						  ModelName: '',
						  MaterialName: '',
							orgNumber: that.orgInfo.orgId
						}
						getExecuteServiceAll({json: JSON.stringify(parameters)}).then(ress => {
							if(ress.Material[0].FmaterialName) {
								uni.hideLoading();
								that.showNum = true
								// 输入框清零
								that.goodsNumber = ''
								// 存入赠品字段
								ress.Material.forEach(item => {
									// item.goodsGifts = false
									item.remark = ''
									item.shopCarNum = 0
									item.priceUnit = item.UnitName
									item.priceUnitId = item.UnitFnumber
								})
								that.goodsInfo = ress.Material[0]
							} else {
								uni.showToast({
									title: ress.Material[0].msg,
									icon: 'none'
								});
							}
						})
					}
				});
			},
			// 扫描商品点击添加触发
			numConfirm(code) {
				if(this.orderData.goodsList.some(item => item.FmaterialNumber == code)) {
					this.againShow = true
					this.showNum = false
				} else {
					this.showNum = false
					this.goodsInfo.shopCarNum = this.goodsNumber
					this.orderData.goodsList.push(this.goodsInfo)
				}
			},
			// 二次添加商品触发
			againConfirm() {
				this.againShow = false
				this.goodsInfo.shopCarNum = this.goodsNumber
				this.orderData.goodsList.push(this.goodsInfo)
			},
			againCancel() {
				this.againShow = false
				const index = this.orderData.goodsList.findIndex(item => item.FmaterialNumber == this.goodsInfo.FmaterialNumber)
				this.scrollToItem(index)
			},
			// 供选存货页调用的方法
			xchPages(goodsId) {
				const index = this.orderData.goodsList.findIndex(item => item.FmaterialNumber == goodsId)
				// this.scrollToItem(index)
				setTimeout(() => {
					this.scrollToItem(index).catch(err => {
						console.error('Scroll failed:', err);
					});
				}, 500);
			},
			async scrollToItem(index) {
			  try {
			    console.log('scrollToItem called with index:', index);
			    // 使用正确的页面上下文进行查询
			    const query = uni.createSelectorQuery().in(this);
			    // 等待DOM更新完成
			    await this.$nextTick();
			    // 封装查询为Promise
			    const [itemRect, scrollOffset] = await new Promise((resolve, reject) => {
			      query.select(`#item-${index}`).boundingClientRect();
			      query.selectViewport().scrollOffset();
			      query.exec(res => {
			        console.log('Selector query result:', res);
			        if (!res || !res[0] || !res[1]) {
			          reject(new Error(`Element #item-${index} not found or scroll offset unavailable`));
			          return;
			        }
			        resolve(res);
			      });
			    });
			    // 计算目标滚动位置
			    const offset = 260;
			    const targetScrollTop = Math.max(0, scrollOffset.scrollTop + itemRect.top - offset);
			    console.log(`Scrolling to: ${targetScrollTop}px (current: ${scrollOffset.scrollTop}px, element top: ${itemRect.top}px)`);
			    // 执行滚动并等待完成
			    await new Promise((resolve, reject) => {
			      uni.pageScrollTo({
			        scrollTop: targetScrollTop,
			        duration: 300,
			        success: resolve,
			        fail: reject
			      });
			    });
			    console.log('Scroll completed successfully');
			  } catch (error) {
			    console.error('Error during scroll:', error);
			    // 可选：添加重试机制
			    this.retryScroll(index);
			  }
			},
			// 结算
			toPay() {
				let FSaleOrderEntry = []
				this.orderData.goodsList.forEach(item => {
					let shopCarNum = item.shopCarNum
					let FAllAmountExceptDisCount = (Number(item.RetailPrice) * Number(item.shopCarNum)).toFixed(2)
					if(this.orderData.userInfo.orderType.id == 'XSDD05_SYS') {
						shopCarNum = Number(item.shopCarNum) * -1
						FAllAmountExceptDisCount = (Number(item.RetailPrice) * Number(item.shopCarNum) * -1).toFixed(2)
					}
					let obj = {
						"FRowType": "Standard",
						"FMaterialId": {
								"FNumber": item.FmaterialNumber
						},
						"FBarcode": item.FmaterialNumber,
						// 单位
						"FUnitID": {
								"FNumber": item.UnitFnumber
						},
						// 备注
						"FEntryNote": item.remark,
						"FQty": shopCarNum,
						"FPriceBaseQty": shopCarNum,
						"FPriceUnitQty" : shopCarNum,
						// 计价单位
						"FPriceUnitId": {
								"FNumber": item.priceUnitId
						},
						"FPrice": item.RetailPrice,
						"FTaxPrice": item.RetailPrice,
						"FDeliveryDate": this.orderData.userInfo.invoicesDate,
						"FStockOrgId": {
								"FNumber": this.orgInfo.orgId
						},
						"FSettleOrgIds": {
								"FNumber": this.orgInfo.orgId
						},
						"FSupplyOrgId": {
								"FNumber": this.orgInfo.orgId
						},
						"FOwnerTypeId": "BD_OwnerOrg",
						"FOwnerId": {
								"FNumber": this.orgInfo.orgId
						},
						"FReserveType": "1",
						"FStockUnitID": {
								"FNumber":  item.UnitFnumber
						},
						"FOUTLMTUNIT": "SAL",
						"FOutLmtUnitID": {
								"FNumber":  item.UnitFnumber
						},
						"FAllAmountExceptDisCount": FAllAmountExceptDisCount,
						"FAllAmount": FAllAmountExceptDisCount,
						"F_PCYE_jgly": "20",
						"F_PCYE_zkl": 0.0,
						"F_PCYE_Amount_83g": 0.0
					}
					FSaleOrderEntry.push(obj)
				})
				let parameters = [
					"SAL_SaleOrder",
					{
						"Model": {
							"FID": this.copyDataId,
							// "FID": this.copyDataId?1:0,
							// "FBillNo": this.copyDataId,
							"FBillTypeID": {
								"FNUMBER": this.orderData.userInfo.orderType.id
							},
							"FDate": this.orderData.userInfo.invoicesDate,
							"FCreateDate": formatTime(new Date()),
							"FSaleOrgId": {
								"FNumber": this.orgInfo.orgId
							},
							"FCustId": {
								"FNumber": this.orderData.userInfo.phone
							},
							"FReceiveId": {
									"FNumber": this.orderData.userInfo.phone
							},
							// 销售员所在部门
							"FSaleDeptId": {
									"FNumber": this.orderData.userInfo.departmentNum
							},
							// 销售员
							"FSalerId": {
									"FNumber": this.orderData.userInfo.salesmanNum
							},
							// 是否开票
							"F_PCYE_ASSISTANT_SFKFP": {
								"FNumber": this.orderData.userInfo.invoiceNum
							},
							"FSettleId": {
									"FNumber": this.orderData.userInfo.phone
							},
							"FChargeId": {
									"FNumber": this.orderData.userInfo.phone
							},
							"FNote": this.orderData.userInfo.remark,
							// 是否积分
							"F_PCYE_CheckBox_re5": true,
							"F_PCYE_Base_83g": {
									"FNUMBER": this.orgInfo.orgId
							},
							"FSaleOrderFinance": {
								// 结算币别
								"FSettleCurrId": {
										"FNumber": "PRE001"
								},
								// 是否含税
								"FIsIncludedTax": true,
								// 价外税
								"FIsPriceExcludeTax": true,
								// 汇率类型
								"FExchangeTypeId": {
										"FNumber": "HLTX01_SYS"
								},
							},
							"FSaleOrderEntry": FSaleOrderEntry,
						}
					}
				]
				if(this.copyDataId) {
				  delete	parameters[1].Model.FSaleOrgId
				}
				uni.showLoading({ mask: true });
				dynamicFormServiceSave({parameters}).then(res => {
					if(res.Result.ResponseStatus.IsSuccess) {
						uni.showToast({
							title: '结算成功',
							icon: "success",
						});
						// 清除销售订单自动恢复的缓存
						uni.removeStorageSync('orderDataCache')
						const Id = res.Result.ResponseStatus.SuccessEntitys[0].Id
						const Number = res.Result.ResponseStatus.SuccessEntitys[0].Number
						setTimeout(function() {
							uni.redirectTo({
							  url: '/other/salesOrder/saleOrderDetail?fid='+Id+"&Number="+Number
							});
						}, 1500)
					} else {
						uni.showToast({
							title: res.Result.ResponseStatus.Errors[0].Message,
							icon: 'none'
						});
					}
				})
			},
			// 获取计价单位
			unitClick(item, index) {
				this.unitIndex = index
				this.columns = []
				uni.showLoading({ mask: true });
				const parameters = [
					{
						"FormId": "BD_UNIT",
						"FieldKeys": "fnumber,fname",
						"FilterString": "FUnitGroupId.fname='" + item.UnitName + "'",
						"OrderString": "",
						"TopRowCount": 0,
						"StartRow":0,
						"Limit": 2000,
						"SubSystemId": ""
					}
				]
				getMaterialInformation({parameters}).then(res => {
					this.unitShow = true
					uni.hideLoading();
					let arr = []
					res.forEach(item => {
						let obj = {}
						obj.name = item[1]
						obj.id = item[0]
						arr.push(obj)
					})
					this.columns.push(arr)
				})
			},
			confirmUnit(e) {
				this.orderData.goodsList[this.unitIndex].priceUnit = e.value[0].name
				this.orderData.goodsList[this.unitIndex].priceUnitId = e.value[0].id
				this.unitShow = false
			},
			imageBig(idCode) {
				uni.showLoading({ mask: true });
				getExecuteServiceImg({ "parameters": [ {"MaterialNumber":idCode, "token":uni.getStorageSync('token')} ]}).then(res => {
					function getQueryParam(url, param) {
						// 构造正则表达式，匹配 ? 或 & 后面跟随的参数名称和其值
						const regex = new RegExp('[?&]' + param + '=([^&#]*)', 'i');
						const result = regex.exec(url);
						return result ? decodeURIComponent(result[1]) : null;
					}
					getBaseImg({ "parameters": [ {"FileId": getQueryParam(res.Url, 'fileId'), "StartIndex": 0 } ]}).then(bres => {
						if(bres.Result.FilePart) {
							uni.hideLoading();
							this.overlayImg = 'data:image/png;base64,' + bres.Result.FilePart
							this.overlayShow = true
						} else {
							uni.showToast({
								title: "暂无图片",
								icon: 'none'
							});
						}
					})
				})
			},

			saveBase64ToPhotoAlbum(base64Data) {
				// 1. 去除Base64头部信息（如："data:image/png;base64,"）
				const base64 = base64Data.replace(/^data:image\/\w+;base64,/, '');
				// 2. 转换为ArrayBuffer
				const arrayBuffer = uni.base64ToArrayBuffer(base64);
				// 3. 生成临时文件路径
				const filePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.png`;
				// 4. 写入文件
				const fs = uni.getFileSystemManager();
				return new Promise((resolve, reject) => {
					fs.writeFile({
					filePath,
					data: arrayBuffer,
					encoding: 'binary',
					success: () => {
						// 5. 保存到相册
						uni.saveImageToPhotosAlbum({
							filePath,
							success: () => resolve('保存成功'),
							fail: (err) => reject('保存失败，请检查权限：' + err.errMsg),
						});
					},
					fail: (err) => reject('文件写入失败：' + err.errMsg),
					});
				});
			},
			async saveBase() {
				try {
					const base64 = this.overlayImg;
					await this.saveBase64ToPhotoAlbum(base64);
					uni.showToast({ title: '保存成功', icon: 'success' });
					console.error("保存图片成功");
				} catch (error) {
					console.error("保存图片失败 error：", error);
					uni.showToast({ title: error, icon: 'none' });
					// 处理权限被拒绝的情况
					if (error.includes('authorize')) {
					uni.openSetting({}); // 引导用户打开权限设置
					}
				}
			},
			// 商品详情
			toForm(item) {
				this.goodsInfoShow = true
				uni.showLoading({ mask: true });
				// 物料编码：Materidal。规格型号：ModelName。物料名称：MaterialName
				const parameters = {
					Materidal: item.FmaterialNumber,
					ModelName: '',
					MaterialName: '',
					orgNumber: this.orgInfo.orgId
				}
				getExecuteServiceAll({json: JSON.stringify(parameters)}).then(res => {
					if(res.Material[0].FmaterialName) {
						uni.hideLoading();
						this.goodsForm = res.Material[0]
						this.goodsForm.priceUnit = item.priceUnit
					} else {
						uni.showToast({
							title: res.Material[0].msg,
							icon: 'none'
						});
					}
				})
			},
	    invoiceSelect(e) {
				this.showInvoice = false
				this.orderData.userInfo.invoice = e.value[0].AssistantName
				this.orderData.userInfo.invoiceNum = e.value[0].AssistantNumber
			},
			orderConfirm(e) {
				this.showOrderType = false
				this.orderData.userInfo.orderType = e.value[0]
			},
			toPage(item) {
				this.jumpTo('/pages/inventoryQuery/inventoryQuery', {orgId: this.orgInfo.orgId, Materidal: item.FmaterialNumber, type: '1'})
			},
	  }
	}
</script>

<style lang="scss" scoped>

	::v-deep .u-form-item__body__left {
		width: auto !important;
		margin-right: 20rpx;
	}
	::v-deep .u-line {
		transform: scaleY(1) !important;
	}
	::v-deep .u-modal__content {
		padding-left: 28rpx !important;
		padding-right: 28rpx !important;
	}
	.pages{
		width: 750rpx;
		min-height: 100vh;
		padding-bottom: 40rpx;
		.top-search {
			display: flex;
			align-items: center;
			justify-content: space-between;
			background-color: #d7dbd6;
			padding: 20rpx 30rpx;
			::v-deep .u-input {
				height: 75rpx;
				background-color: #fff;
				padding-left: 80rpx !important;
			}
			.search-type {
			  width: 180rpx;
			  font-size: 28rpx;
			  display: flex;
			  align-items: center;
			  gap: 6rpx;
			}
			.top-input {
				position: relative;
				width: 450rpx;
				.btn {
					position: absolute;
					top: 0;
					right: 20rpx;
					height: 75rpx;
					line-height: 75rpx;
					z-index: 99;
				}
				image {
					position: absolute;
					top: 20rpx;
					left: 24rpx;
					width: 40rpx;
					height: auto;
				}
			}
		}
		.form-data {
			margin: 0 40rpx 20rpx;
			.radio {
				margin-top: 20rpx;
			}
			.foldBtn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 200rpx;
				padding: 10rpx 0;
				border: 1px solid #d7dbd6;
				border-radius: 30rpx;
				margin: 26rpx auto 0;
			}
		}
		.goods-box {
			margin-bottom: 260rpx;
			.title {
				width: 100%;
				height: 50rpx;
				line-height: 50rpx;
				background-color: #eee6e7;
				padding: 0 20rpx;
				margin-top: 20rpx;
			}
			.goods-data {
				.goods-list {
					width: 100%;
					padding: 20rpx 30rpx;
					border-bottom: 1px solid #5f6061;
					.list-name {
						display: flex;
						justify-content: space-between;
						align-items: center;
						.name {
							width: 80%;
							font-size: 32rpx;
						}
					}
					.list-price {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin: 10rpx 0 20rpx;
						.price {
							width: 48%;
							display: flex;
							align-items: center;
						}
						.number {
							width: 48%;
							display: flex;
							align-items: center;
						}
						.textarea {
							width: 90%;
							display: flex;
							align-items: center;
						}
					}
					.form {
						display: flex;
						justify-content: space-between;
					}
					.stocksBtn {
						width: 230rpx;
						line-height: 50rpx;
						border: 1px solid #2677f0;
						border-radius: 10rpx;
						color: #2677f0;
						margin-left: auto;
					}
				}
			}
			.goods-null {
				width: 100%;
				min-height: 500rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				text-align: center;
			}
		}
		.bottom-box {
			position: fixed;
			bottom: 0;
			background-color: #fff;
			width: 100%;
			z-index: 9;
			.top-list {
				background-color: #e4c5aa;
				padding: 20rpx 40rpx;
			}
			.list {
				display: flex;
				padding-bottom: 60rpx;
				font-size: 30rpx;
				.one {
					flex: 1;
					height: 100rpx;
					line-height: 100rpx;
					text-align: center;
				}
				.two {
					flex: 1;
					height: 100rpx;
					line-height: 100rpx;
					border-left: 1px solid #d7dbd6; 
					border-right: 1px solid #d7dbd6; 
					text-align: center;
				}
				.three {
					flex: 1;
					height: 100rpx;
					line-height: 100rpx;
					color: #fff;
					background-color: #2677f0;
					text-align: center;
				}
			}
		}
	}
	.goodsNum-modal {
		width: 100%;
		line-height: 50rpx;
	}
	.overlayImage {
		width: 80%;
		height: auto;
		margin: 300rpx auto 50rpx;
	}
	.saveBase {
		width: 200rpx;
		height: 60rpx;
    line-height: 60rpx;
    color: #fff;
    background-color: #2677f0;
    text-align: center;
		border-radius: 50rpx;
		margin: 0 auto;
	}
	.goodsView {
		width: 100%;
		.goods-info {
			display: flex;
			justify-content: space-between;
			align-items: center;
			line-height: 45rpx;
			.sum {
				display: flex;
				align-items: center;
				margin-top: 16rpx;
				.actionDown {
					width: 50rpx;
					height: 50rpx;
					border-radius: 50rpx;
					border: 2rpx solid #266be9;
					font-size: 50rpx;
					color: #266be9;
					display: flex;
					justify-content: center;
				}
				.sum-text {
					margin: 0 10rpx;
				}
				.actionUp {
					width: 50rpx;
					height: 50rpx;
					border-radius: 50rpx;
					border: 2rpx solid #266be9;
					background-color: #266be9;
					font-size: 40rpx;
					color: #fff;
					display: flex;
					justify-content: center;
				}
			}
		}
	}
</style>